//
//  WCFileMenuController.m
//  WabbitCode
//
//  Created by William Towe on 2/3/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCFileMenuController.h"
#import "WCDocumentController.h"
#import "WCProject.h"
#import "WCMacros.h"
#import "WCTabViewContextProtocol.h"


@implementation WCFileMenuController

- (BOOL)validateMenuItem:(NSMenuItem *)item {
	SEL action = [item action];
	
	if (action == @selector(closeAction:)) {
		if (![NSApp mainWindow])
			return NO;
	}
	else if (action == @selector(closeProjectAction:)) {
		if (![NSApp mainWindow])
			return NO;
	}
	return YES;
}

- (IBAction)closeAction:(id)sender; {
	NSWindow *window = [NSApp keyWindow];
	WCProject *project = [[WCDocumentController sharedDocumentController] currentProject];
	
	if ([window isEqualTo:[project projectWindow]] ||
		[[window windowController] conformsToProtocol:@protocol(WCTabViewContext)]) {
		
		NSObject <WCTabViewContext> *context = [project currentTabViewContext];
		if ([context numberOfTabViewItems]) {
			if (![project canRemoveTabViewItem:[context currentTabViewItem] inTabViewContext:context])
				return;
			
			[[context tabView] removeTabViewItem:[[context tabView] selectedTabViewItem]];
		}	
		else {
			[window performClose:nil];
		}
	}
	else {
		[window performClose:nil];
	}
}

- (IBAction)closeProjectAction:(id)sender; {
	[[NSApp keyWindow] performClose:nil];
}
@end
